# 开发时间 2023/6/16 15:41
import mysql.connector
import mysql.connector.pooling
from threading import Semaphore
from contextlib import contextmanager

mysql_config = {
    'user': 'root',
    'password': 'root',
    'host': 'localhost',
    'port': '3306',
    'database': 'python_code'
}


class ReallyMySQLConnectionPool(mysql.connector.pooling.MySQLConnectionPool):
    def __init__(self, **mysql_config):
        pool_size = mysql_config.get('pool_size', 10)
        self._semaphore = Semaphore(pool_size)
        super().__init__(**mysql_config)

    def get_connection(self):
        self._semaphore.acquire()
        return super().get_connection()

    def put_connection(self, con):
        con.close()  # con是PooledMySQLConnection的实例
        self._semaphore.release()


cnxpool = ReallyMySQLConnectionPool(**mysql_config, pool_name="mypool", pool_size=10,
                                    connection_timeout=30)


@contextmanager
def get_cursor():
    try:
        con = cnxpool.get_connection()
        cursor = con.cursor()
        yield cursor
    except mysql.connector.Error as err:
        print('errno={}'.format(err))

    finally:
        cursor.close()
        cnxpool.put_connection(con)


class PyMysql(object):
    @staticmethod
    def get_all(sql):
        with get_cursor() as cursor:
            cursor.execute(sql)
            return cursor.fetchall()


'''if __name__ == '__main__':
    import time
    from concurrent.futures import ThreadPoolExecutor


    def t(n):
        r1 = PyMysql.get_all("select * from TABLE")
        print(str(n) + str(r1))


    s = time.time()
    with ThreadPoolExecutor(max_workers=15) as pool:
        for i in range(20):
            pool.submit(t, (i))

    print(time.time() - s)'''